var Q = require('q');


/* 从网络读取文件内容 */
var readFromNet = function (url, callback){
  console.log('\nrequest remote file from %s \n',url);
  callback('remote content');
};

/* 保存为本地文件 */
var saveToDisk = function (content, callback){
  console.log('\nsave %s to local file %s \n', content, '/path/to/file');
  callback('/path/to/file');
};

/* 组装文件信息返回给用户 */
var returnToUser = function (fileName, callback){
  console.log('\nreturn file %s to user \n', fileName);
  callback({path:fileName,status:200});
};


var readFromNetQ = function (url){
  var deferred = Q.defer();
  readFromNet(url, function (content){
    if(!!content){
      deferred.resolve(content);
    }
  })
  return deferred.promise;
};

var saveToDiskQ = function (content){
  var deferred = Q.defer();
  saveToDisk(content, function (fileName){
    if(!!fileName){
      deferred.resolve(fileName);
    }
  })
  return deferred.promise;
};

var returnToUserQ = function (fileName){
  var deferred = Q.defer();
  returnToUser(fileName, function (data){
    if(!!data){
      deferred.resolve(data);
    }
  })
  return deferred.promise;
};


exports.requestFileQ = function (url){
  var deferred = Q.defer(); 
  readFromNetQ(url)
  .then(function (content){
    return saveToDiskQ(content);
  })
  .then(function (fileName){
    return returnToUserQ(fileName);
  })
  .then(function (data){
    deferred.resolve(data);
  })
  .done();
  return deferred.promise;
};

exports.requestFile = function (url, callback){
  readFromNet(url ,function (content){
    //callback 1
    saveToDisk(content ,function (fileName){
      //callback 2
      returnToUser(fileName, function (data){
        //callback 3
        callback(data);//callback 4
      });
    });
  });
};

